<?php
/**
 * Created by PhpStorm.
 * User: xiong
 * Date: 2018/2/5
 * Time: 16:32
 */

namespace App\Http\Controllers\Api;

use App\ApiResponse;
use App\Helper;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\User;
use Auth;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use ApiResponse;

    public function login(Request $request)
    {
        $user = User::wherePhone($request->username)->first();
        if ($user) {
            if (!\Hash::check($request->password, $user->password)) {
                return response()->json(['msg' => '账号密码错误'], 400);
            }
            if ($user->status) {
                $access_token = \JWTAuth::fromUser($user);
                return response()->json(['msg' => '登录成功', 'data' => ['token' => $access_token, 'user' => new UserResource($user)]], 200);
            } else {
                return $this->message('您的账号暂未审核，请等待审核后再试', 400);
            }

        } else {
            return response()->json(['msg' => '用户名不存在'], 400);
        }
    }

    public function find(Request $request)
    {

        /** @var \App\Models\User $user */
        $user = User::wherePhone($request->username)->first();
        if ($user) {
            $isCheck = Helper::checkSmsCode($user->phone, $request->sms_code);
            if (!$isCheck) {
                return response()->json(['msg' => '验证码错误'], 400);
            }
            $user->password = bcrypt($request->password);
            $user->save();
            return $this->message("重置密码成功");
        }else {
            return $this->message("账号不存在",[],400);
        }
    }
}